'use strict'

const {Blogs,Op}=require('../model')
//通过关键字查询
let fn_list=async(ctx,next)=>{
    let keyword=ctx.request.query.keyword || '';
    if(keyword){
        let list;
        list =await Blogs.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword) ?0 :parseInt(keyword)},
                    {title:keyword},
                    {abstract:keyword},
                    {content:keyword},
                    {classify:keyword},
                    {author:keyword},
                ]
            },
            order:['id']
        })
        ctx.body={
            code:1000,
            data:list,
            msg:'查询成功'
        }
    }else{
        let list=await Blogs.findAll({
            order:['id']
        })
        ctx.body={
            code:1000,
            data:list,
            msg:'查询成功'
        }
    }
}

let fn_getbyid=async(ctx,next)=>{
    let id=ctx.request.params.id;
    let product=await Blogs.findByPk(id)
    if(product){
        ctx.body={
            code:1000,
            data:product,
            msg:'查询成功'
        }
    }else{
        ctx.body={
            code:900,
            data:'',
            msg:'查询失败'
        }
    }
}
let fn_post=async(ctx,next)=>{
    let obj=ctx.request.body;
    await Blogs.create(obj)
    ctx.body=obj;
}
let fn_put=async(ctx,next)=>{
    let id=ctx.request.params.id;
    let obj=ctx.request.body;
    let product=await Blogs.findByPk(id)
    if(product){
        Blogs.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:product,
            msg:"更新成功"
        }
    }else{
        ctx.body={
            code:900,
            data:'',
            msg:'查询失败'
        }
    }  
}
let fn_delete=async(ctx,next)=>{
    let id=ctx.request.params.id;
    let product=await Blogs.findByPk(id)
    if(product){
        Blogs.destroy({
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:{id},
            msg:"删除成功"
        }
    }else{
        ctx.body={
            code:900,
            data:'',
            msg:'删除失败'
        }
    }  
}


module.exports={
    'get /blog':fn_list,
    'get /blog/:id':fn_getbyid,
    'post /blog':fn_post,
    'put /blog/:id':fn_put,
    'delete /blog/:id':fn_delete
}
